import { TimeObserver } from "./TimeObserver";
import TimeHelper from "./TimeHelper";

/**
 * 时间递减
 */
export default class TimerDecrement extends TimeObserver {
    protected temp: number = 0;
    protected totalTime: number = 0;
    /**
    * 
    * @param endTime 结束时间
    * @param isTimeStamp 结束时间是否是时间戳
    */
    setTime(endTime: number, isTimeStamp: boolean = true) {
        if (isTimeStamp) {
            this.time = Math.floor(TimeHelper.leftTime(endTime) / 1000);
        } else {
            this.time = endTime
        }
        this.totalTime = this.time;
        if (this.time < 0) {
            this.time = 0;
        }
    }

    getPercent() {
        if (this.totalTime == 0) {
            return 0;
        }
        return (this.totalTime - this.time) / this.totalTime
    }

    check(dt: number) {
        if (this.time > 0) {
            this.temp += dt;
            if (this.temp >= this.duration) {
                let per = Math.floor(this.temp / this.duration)
                this.temp -= per
                this.time -= per
                if (this.time < 0) {
                    this.time = 0;
                }
                if (this.func) {
                    this.func(this.time);
                }
            }
            return false
        } else {
            return true;
        }
    }
}
